package cn.edu.jju.stepcounter2;


import android.content.Context;
import android.os.Looper;
import android.os.Process;
import android.os.SystemClock;

import cn.edu.jju.stepcounter2.utils.AppManager;
import cn.edu.jju.stepcounter2.utils.ShowToastUtil;

/**
 * Created by roor on 2016/12/19.
 */

public class CrashHandler implements
        Thread.UncaughtExceptionHandler {

    private static Object lock = new Object();
    private Context mContext;

    private CrashHandler() {
        // Empty Constractor
    }

    private static CrashHandler mCrashHandler;


    public static CrashHandler getInstance() {
        synchronized (lock) {
            if (mCrashHandler == null) {
                synchronized (lock) {
                    if (mCrashHandler == null) {
                        mCrashHandler = new CrashHandler();
                    }
                }
            }

            return mCrashHandler;
        }
    }

    /* 初始化 */
    public void init(Context context) {
        this.mContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, final Throwable ex) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                Looper.prepare();

                ShowToastUtil.showToast(mContext,"程序发生了点小意外，即将关闭... " +
                        ex.getMessage());
                Looper.loop();

                SystemClock.sleep(3000);

                // 将Activity的栈清空
                AppManager.getAppManager().finishAllActivity();


                // 退出程序
                Process.killProcess(Process.myPid());
                // 关闭虚拟机，彻底释放内存空间
                System.exit(0);

            }
        }).start();
    }



}